package com.briup.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.DTO.SaveOrUpdateAnimalDTO;
import com.briup.VO.AnimalFindByIdVO;
import com.briup.VO.AnimalQueryListVO;
import com.briup.constant.SystemConstant;
import com.briup.enums.CodeAndMessageEnum;
import com.briup.exception.SystemException;
import com.briup.mapper.AnimalMapper;
import com.briup.mapper.BatchMapper;
import com.briup.mapper.FenceHouseMapper;
import com.briup.mapper.HurdlesMapper;
import com.briup.pojo.*;
import com.briup.result.PageTemplate;
import com.briup.result.Result;
import com.briup.service.AnimalService;
import com.briup.service.FenceHouseService;
import com.briup.service.HurdlesService;
import com.briup.service.QrcodeService;
import com.briup.util.BeanCopyUtils;
import com.briup.util.QRCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Lenovo
 * @description 针对表【manager_animal】的数据库操作Service实现
 * @createDate 2024-03-13 14:29:39
 */
@Service
@Slf4j
public class AnimalServiceImpl extends ServiceImpl<AnimalMapper, Animal>
        implements AnimalService {

    @Autowired
    private AnimalMapper animalMapper;
    //注入批次相关Mapper层对象
    @Autowired
    private BatchMapper batchMapper;

    //注入栏舍相关Mapper层对象
    @Autowired
    private FenceHouseMapper fenceHouseMapper;

    //注入栏圈相关Mapper层对象
    @Autowired
    private HurdlesMapper hurdlesMapper;

    @Autowired
    private QrcodeService qrcodeService;

    @Autowired
    private HurdlesService hurdlesService;

    @Autowired
    private FenceHouseService fenceHouseService;

    @Override
    public PageTemplate animalQuery(Integer pageNum, Integer pageSize, String aHealthy, String aGender) throws SystemException {
        //参数校验
        if (Objects.isNull(pageNum) || Objects.isNull(pageSize)) {
            //页码或页面大小为空
            throw new SystemException(CodeAndMessageEnum.PAGE_NUMBER_OR_PAGE_SIZE_IS_NULL);
        }
        //创建分页对象
        Page<Animal> animalPage = new Page<>(pageNum, pageSize);
        //创建条件构造器
        LambdaQueryWrapper<Animal> animalLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //构造条件
        animalLambdaQueryWrapper
                //根据健康状态等值比较
                .eq(Objects.nonNull(aHealthy) && StringUtils.hasText(aHealthy), Animal::getaHealthy, aHealthy)
                //根据性别等值比较
                .eq(Objects.nonNull(aGender) && StringUtils.hasText(aGender), Animal::getaGender, aGender);
        //核心查询
        animalMapper.selectPage(animalPage, animalLambdaQueryWrapper);
        //查询全部二维码信息
        List<Qrcode> qrcodes = qrcodeService.list();
        List<Animal> animals = animalPage.getRecords();
        for (Animal animal : animals) {
            //筛选出来指定的二维码
            List<Qrcode> list = qrcodes.stream().filter(qrcode -> qrcode.getQAnimalId().equals(animal.getaAnimalId())).collect(Collectors.toList());
            if (list.isEmpty()) {
                //为空
                continue;
            } else {
                //找到了
                animal.setaBackup3(list.get(SystemConstant.FIRST_ELEMENT_INDEX).getQImageUrl());
            }
        }
        //Bean拷贝
        List<AnimalQueryListVO> animalQueryPageListVOS = BeanCopyUtils.copyBeanList(animals, AnimalQueryListVO.class);
        //查询所有的栏圈信息
        List<Hurdles> hurdles = hurdlesService.list();
        //查询所有的栏舍信息
        List<FenceHouse> fenceHouses = fenceHouseService.list();
        for (AnimalQueryListVO animalQueryPageListVO : animalQueryPageListVOS) {
            Hurdles h = hurdles.stream().filter(hurdles1 -> hurdles1.getHId().equals(animalQueryPageListVO.getaHurdlesId())).collect(Collectors.toList()).get(SystemConstant.FIRST_ELEMENT_INDEX);
            //查询栏圈名称
            animalQueryPageListVO.setManagerHurdles(h.getHName());
            //查询栏舍名称
            animalQueryPageListVO.setManagerFenceHouse(fenceHouses.stream().filter(fenceHouse -> fenceHouse.getFhId().equals(h.getHFenceId())).collect(Collectors.toList()).get(SystemConstant.FIRST_ELEMENT_INDEX).getFhName());
        }
        return new PageTemplate(animalPage.getTotal(), animalQueryPageListVOS);
    }



    @Override
    public void generateQRCodeByAnimal(String animalId) throws SystemException {
        //判断动物信息是否存在
        Animal animal = animalMapper.selectById(animalId);
        if (Objects.isNull(animal)){
            throw new SystemException(CodeAndMessageEnum.ANIMAL_INFO_IS_NOT_EXIST);
        }
        String fileName = null;
        try {
            fileName=QRCodeUtils.generateLogoQRCode(animalId, SystemConstant.WIDTH, SystemConstant.HEIGHT, SystemConstant.TYPE, SystemConstant.LOGO_TARGET, SystemConstant.GENERATE_QRCODE_TARGET);
        } catch (Exception e) {
            throw new SystemException(CodeAndMessageEnum.QRCODE_GENERATE_ERROR);
        }
        //添加二维码信息
        qrcodeService.addQRCode(animalId,SystemConstant.BASE_QRCODE_URL+fileName);
    }

    @Override
    public AnimalFindByIdVO findByAnimalId(String animalId) throws SystemException {
        //根据动物Id查询动物信息
        Animal animal = animalMapper.selectById(animalId);
        /*
         * 根据动物中的批次ID查询批次信息
         */
        //根据动物对象中的批次ID查询批次信息
        Batch batch = batchMapper.selectById(animal.getaBatchId());

        /*
         * 根据动物中的栏圈ID查询栏圈信息
         */
        //根据动物信息中的栏圈ID查询栏圈信息
        Hurdles hurdles = hurdlesMapper.selectById(animal.getaHurdlesId());

        /*
         * 根据栏圈中的栏舍ID查询栏舍信息
         */
        FenceHouse fenceHouse = fenceHouseMapper.selectById(hurdles.getHFenceId());

        /*
         * 信息封装
         */
        //bean拷贝将动物信息封装在VO对象
        AnimalFindByIdVO animalFindByIdVO = BeanCopyUtils.copyBean(animal, AnimalFindByIdVO.class);
        //封装批次信息到VO对象
        animalFindByIdVO.setManagerBatch(batch);
        //封装栏圈名称到VO对象
        animalFindByIdVO.setManagerHurdles(hurdles.getHName());
        //封装栏舍名称到VO对象
        animalFindByIdVO.setManagerFenceHouse(fenceHouse.getFhName());
        //返回统一响应
        return animalFindByIdVO;
    }

    @Override
    public Result animalSaveOrUpdate(SaveOrUpdateAnimalDTO saveOrUpdateAnimalDTO) throws SystemException {
        Animal animal = BeanCopyUtils.copyBean(saveOrUpdateAnimalDTO, Animal.class);
        String hurdlesId = animal.getaHurdlesId();
        Hurdles hurdles = hurdlesMapper.selectById(hurdlesId);
        if (hurdles.getHSaved().equals(hurdles.getHMax())){
            throw new SystemException(CodeAndMessageEnum.HURDLES_IS_FULL);
        }
        if (StringUtils.hasText(saveOrUpdateAnimalDTO.getaAnimalId())){
            //有动物ID信息  修改操作
            animalMapper.updateById(animal);
            //返回成功响应数据
            return Result.success();
        }else{
            //不含有动物ID信息  新增操作
            animalMapper.insert(animal);
            //返回成功响应数据
            return Result.success();
        }
    }

    @Override
    public Result deleteById(String id) throws SystemException {
        Animal animal = animalMapper.selectById(id);
        if (Objects.isNull(animal)) {
            throw new SystemException(CodeAndMessageEnum.ANIMAL_INFO_IS_NOT_EXIST);
        }
        animalMapper.deleteById(id);
        return Result.success();
    }

    @Override
    public Result deleteByIdAll(List<String> ids) throws SystemException {
        LambdaQueryWrapper<Animal> animalLambdaQueryWrapper = new LambdaQueryWrapper<>();
        animalLambdaQueryWrapper.in(Objects.nonNull(ids) && !ids.isEmpty(), Animal::getaAnimalId, ids);
        List<Animal> animalList = animalMapper.selectList(animalLambdaQueryWrapper);
        if (ids.size() != animalList.size()) {
//            有id找不到对应的信息
            throw new SystemException(CodeAndMessageEnum.ANIMAL_INFO_IS_NOT_EXIST);
        }
        animalMapper.deleteBatchIds(ids);
        return Result.success();
    }
}




